package main

import (
	"fmt"
	"github.com/go-redis/redis"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/logger"
	"github.com/kataras/iris/v12/middleware/recover"
	"github.com/kataras/iris/v12/sessions"
	"os"
	"strconv"
	"wemall/config"
	"wemall/model"
	"wemall/route"
)

func init() {
	var (
		cookieNameForSessionID = "mycookiesessionnameid"
		sess                   = sessions.New(sessions.Config{Cookie: cookieNameForSessionID})
	)
	db, err := gorm.Open(config.DBConfig.Dialect, config.DBConfig.URL)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(-1)
	}

	if config.DBConfig.SQLLog {
		db.LogMode(true)
	}

	db.DB().SetMaxIdleConns(config.DBConfig.MaxIdleConns)
	db.DB().SetMaxOpenConns(config.DBConfig.MaxOpenConns)

	model.DB = db
	config.Sess = sess

	config.Rdb = redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password set
		DB:       0,  // use default DB
	})
	_, err = config.Rdb.Ping().Result()
	if err != nil {
		fmt.Println(err)
	}
}

// Cors
func Cors(ctx iris.Context) {
	ctx.Header("Access-Control-Allow-Origin", "*")
	//ctx.Header("Access-Control-Allow-Headers","DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization")
	//ctx.Header("Access-Control-Allow-Methods","GET,POST,OPTIONS,HEAD,DELETE")
	if ctx.Method() == "OPTIONS" {
		ctx.Header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,PATCH,OPTIONS")
		ctx.Header("Access-Control-Allow-Headers", "Content-Type,Accept,Authorization")
		ctx.StatusCode(204)
		return
	}
	ctx.Next()
}

func main() {
	app := iris.New()

	// 解决跨域的主要代码
	//c := cors.New(cors.Options{
	//	AllowedOrigins:   []string{"*"},
	//	AllowCredentials: true,
	//	Debug:            true,
	//})
	//app.WrapRouter(c.ServeHTTP)
	app.Use(Cors)
	// 日志监控
	app.Use(recover.New())
	app.Use(logger.New())

	//if config.ServerConfig.Debug {
	//	app.Adapt(iris.DevLogger())
	//}

	//app.Adapt(sessions.New(sessions.Config{
	//	Cookie: config.ServerConfig.SessionID,
	//	Expires: time.Minute * 20,
	//}))

	//app.Adapt(httprouter.New())

	route.Route(app)

	//app.OnError(iris.StatusNotFound, func(ctx *iris.Context) {
	//	ctx.JSON(iris.StatusOK, iris.Map{
	//		"errNo" : model.ErrorCode.NotFound,
	//		"msg"   : "Not Found",
	//		"data"  : iris.Map{},
	//	})
	//
	//})
	//
	//app.OnError(500, func(ctx *iris.Context) {
	//	ctx.JSON(iris.StatusInternalServerError, iris.Map{
	//		"errNo" : model.ErrorCode.ERROR,
	//		"msg"   : "error",
	//		"data"  : iris.Map{},
	//	})
	//})

	app.Listen(":" + strconv.Itoa(config.ServerConfig.Port))
}
